package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.FriendApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Friend friend1, Friend friend2) {

        Query query1 = new Query(Criteria.where("userId").is(friend1.getUserId()).and("friendId").is(friend1.getFriendId()));
        Query query2 = new Query(Criteria.where("userId").is(friend2.getUserId()).and("friendId").is(friend2.getFriendId()));

        if (!mongoTemplate.exists(query1,Friend.class)) {
            mongoTemplate.save(friend1);
        }
        if (!mongoTemplate.exists(query2,Friend.class)) {
            mongoTemplate.save(friend2);
        }
    }

    @Override
    public PageResult queryFriends(Integer page, Integer pagesize, Long userId, String keyword) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page - 1)*pagesize);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        return new PageResult(page,pagesize,(int)count,friends);
    }

    @Override
    public Integer remove(Long userId, Integer friendId) {
        Query q1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        Query q2 = new Query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        Integer num = 0;
        if (mongoTemplate.exists(q1, Friend.class)){
            mongoTemplate.remove(q1,Friend.class);
            num = 1;
            if(mongoTemplate.exists(q2, Friend.class)){
                mongoTemplate.remove(q2,Friend.class);
                num = 2;
            }
        }
        return num;
    }
}
